package com.example.feifei.newproject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.feifei.bean.AdressBean;
import com.example.feifei.net.ApiService;
import com.example.feifei.utils.LocationUtils;
import com.example.feifei.utils.LogUtils;
import com.yanzhenjie.album.Album;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import io.card.payment.CardIOActivity;
import io.card.payment.CreditCard;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018\7\12 0012.
 */

public class BankScanActivity extends Activity {
    //银行卡扫描返回结果标志
    private static final int MY_SCAN_REQUEST_CODE = 10;
    //第三方照片返回标志
    private static final int ACTIVITY_REQUEST_SELECT_PHOTO = 9;
    //自定义照片返回标志
    private static final int ACTIVITY_MYPICTURE = 8;

    private Button btn_scan;
    private Button btn_picture;
    private TextView text_picPath;
    private Button btn_mypicture;
    private TextView location_juli;
    private EditText input_address;
    private Button btn_getlocation;
    private TextView get_fromaddress;
    private Button btn_scrollEdit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bankscan);
        initView();
    }

    private void initView() {
        btn_scan = (Button) this.findViewById(R.id.btn_scan);
        btn_picture = (Button) this.findViewById(R.id.btn_picture);
        //银行卡扫描，io.card，准确率并不高
        btn_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent scanIntent = new Intent(BankScanActivity.this, CardIOActivity.class);

                // customize these values to suit your needs.
                scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_EXPIRY, true); // default: false
                scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_CVV, false); // default: false
                scanIntent.putExtra(CardIOActivity.EXTRA_REQUIRE_POSTAL_CODE, false); // default: false

                // MY_SCAN_REQUEST_CODE is arbitrary and is only used within this activity.
                startActivityForResult(scanIntent, MY_SCAN_REQUEST_CODE);
            }
        });
        //系统图片相册选择
        btn_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Album.startAlbum(BankScanActivity.this, ACTIVITY_REQUEST_SELECT_PHOTO
                        , 9                                                         // 指定选择数量。
                        , ContextCompat.getColor(BankScanActivity.this, R.color.colorPrimary)        // 指定Toolbar的颜色。
                        , ContextCompat.getColor(BankScanActivity.this, R.color.colorPrimaryDark));  // 指定状态栏的颜色。
            }
        });
        //获取两点之间的距离
        btn_mypicture = (Button) this.findViewById(R.id.btn_mypicture);
        location_juli = (TextView) this.findViewById(R.id.location_juli);
        btn_mypicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double juli = LocationUtils.getJuli(Double.valueOf("116.404292"), Double.valueOf("39.915028"), Double.valueOf("116.402998"), Double.valueOf("39.924158"));
                location_juli.setText("两点之间距离=="+String.valueOf(juli));

            }
        });
        //根据输入地址获取经纬度坐标值
        input_address = (EditText) this.findViewById(R.id.input_address);
        btn_getlocation = (Button) this.findViewById(R.id.btn_getlocation);
        get_fromaddress = (TextView) this.findViewById(R.id.get_fromaddress);
        btn_getlocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCityInfo();
            }
        });

        btn_scrollEdit = (Button) this.findViewById(R.id.btn_scrollEdit);
        btn_scrollEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_scrollEdit = new Intent(BankScanActivity.this,ScrollEditTextActivity.class);
                startActivity(intent_scrollEdit);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MY_SCAN_REQUEST_CODE) {
            String resultDisplayStr;
            if (data != null && data.hasExtra(CardIOActivity.EXTRA_SCAN_RESULT)) {
                CreditCard scanResult = data.getParcelableExtra(CardIOActivity.EXTRA_SCAN_RESULT);

                // Never log a raw card number. Avoid displaying it, but if necessary use getFormattedCardNumber()
                resultDisplayStr = "Card Number: " + scanResult.getRedactedCardNumber() + "\n";

                // Do something with the raw number, e.g.:
                // myService.setCardNumber( scanResult.cardNumber );

                if (scanResult.isExpiryValid()) {
                    resultDisplayStr += "Expiration Date: " + scanResult.expiryMonth + "/" + scanResult.expiryYear + "\n";
                }

                if (scanResult.cvv != null) {
                    // Never log or display a CVV
                    resultDisplayStr += "CVV has " + scanResult.cvv.length() + " digits.\n";
                }

                if (scanResult.postalCode != null) {
                    resultDisplayStr += "Postal Code: " + scanResult.postalCode + "\n";
                }
            }
            else {
                resultDisplayStr = "Scan was canceled.";
            }
            // do something with resultDisplayStr, maybe display it in a textView
            // resultTextView.setText(resultDisplayStr);
        }
        // else handle other activity results

        if (requestCode == ACTIVITY_REQUEST_SELECT_PHOTO) {
            if (resultCode == RESULT_OK) { // 判断是否成功。
                // 拿到用户选择的图片路径List：
                String pathInfo = new String();
                List<String> pathList = Album.parseResult(data);
                for(int i = 0;i<pathList.size();i++){
                    LogUtils.e("得到图片路径===="+pathList.get(i).toString());
                }
            } else if (resultCode == RESULT_CANCELED) { // 用户取消选择。
                // 根据需要提示用户取消了选择。
            }
        }
    }

    //根据坐标得到城市信息
    //http://api.map.baidu.com/geocoder?address='北京市东城区景山前街4号'&output=json&key='iQWBRMOXBiUa1WWmGONiGaOZ'
    private void getCityInfo(){
        Retrofit retrofitClient = new Retrofit.Builder()
                .baseUrl("http://api.map.baidu.com")
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiService api = retrofitClient.create(ApiService.class);
        Map<String,String> map = new TreeMap<>();
        map.put("output","json");
        map.put("address",input_address.getText().toString());
        map.put("ak","qBQg1qFBYjQf1Z1kSfCabEGV");
        Observable<AdressBean> observable = api.queryAddress(map);
        observable.subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<AdressBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(AdressBean s) {
//                        Gson gson = new GsonBuilder().create();
//                        AdressBean bean =  gson.fromJson(s,AdressBean.class);
                        if("OK".equals(s.getStatus())){
                            get_fromaddress.setText(s.getResult().getLocation().getLat()+","+s.getResult().getLocation().getLng());
                        }
                    }
                });
    }
}
